/*
  全局工具方法
  每个编写的工具方法必须要写好说明，最好有例子
  通过import {} from 'util.js'有选择导入
  当前拥有的方法有：
  1.根据时间及格式获取时间的字符串（formatDate）
  2.转化时间（transDate）
  3.设置cookie（setCookie）
  4.读取cookie（getCookie）
  5.base64 明文简单加密
  6.base64 明文简单解密
*/
/* 1.根据时间及格式获取时间的字符串
 * @param {int} iDate 时间
 * @param {string} sFormat 格式，默认：yyyy-MM-dd HH:mm:ss
 * @return {string} 格式化后的日期字符串
 * @example formatDate(new Date(),'yyyy-MM-dd HH:mm:ss SSS');// 2017-6-6 11:11:11
 */
export const formatDate = (iDate, sFormat = "yyyy-MM-dd HH:mm:ss") => {
  if (!iDate) {
    return;
  }
  let dDate = new Date(iDate);
  let year = dDate.getFullYear(); // 年
  let month = dDate.getMonth() + 1; // 月
  if (month < 10) {
    month = "0" + month;
  }
  let date = dDate.getDate(); // 日
  if (date < 10) {
    date = "0" + date;
  }
  let hour = dDate.getHours(); // 时
  if (hour < 10) {
    hour = "0" + hour;
  }
  let minute = dDate.getMinutes(); // 分
  if (minute < 10) {
    minute = "0" + minute;
  }
  let second = dDate.getSeconds(); // 秒
  if (second < 10) {
    second = "0" + second;
  }
  let millisecond = dDate.getMilliseconds(); // 毫秒
  if (sFormat.indexOf("yyyy") >= 0) {
    sFormat = sFormat.replace("yyyy", year + "");
  }
  if (sFormat.indexOf("MM") >= 0) {
    sFormat = sFormat.replace("MM", month + "");
  }
  if (sFormat.indexOf("dd") >= 0) {
    sFormat = sFormat.replace("dd", date + "");
  }
  if (sFormat.indexOf("HH") >= 0) {
    sFormat = sFormat.replace("HH", hour + "");
  }
  if (sFormat.indexOf("mm") >= 0) {
    sFormat = sFormat.replace("mm", minute + "");
  }
  if (sFormat.indexOf("ss") >= 0) {
    sFormat = sFormat.replace("ss", second + "");
  }
  if (sFormat.indexOf("SSS") >= 0) {
    sFormat = sFormat.replace("SSS", millisecond + "");
  }
  return sFormat;
};

/* 2.转化时间
 * @param {String} str (yyyy-MM-dd HH:mm:ss SSS)
 * @return {String} 转化后的时间
 * @example transDate("2019-1-10");// 2天前
 */
export const transDate = str => {
  if (!str) return "";
  let date = new Date(str);
  // 现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
  let time = new Date().getTime() - date.getTime();
  if (time < 0) {
    return "";
  } else if (time / 1000 < 30) {
    return "刚刚";
  } else if (time / 1000 < 60) {
    return parseInt(time / 1000) + "秒前";
  } else if (time / 60000 < 60) {
    return parseInt(time / 60000) + "分钟前";
  } else if (time / 3600000 < 24) {
    return parseInt(time / 3600000) + "小时前";
  } else if (time / 86400000 < 31) {
    return parseInt(time / 86400000) + "天前";
  } else if (time / 2592000000 < 12) {
    return parseInt(time / 2592000000) + "月前";
  } else {
    return parseInt(time / 31536000000) + "年前";
  }
};

/* 3.设置cookie
 * @param {string} name cookie名称
 * @param {string} value cookie值
 * @param {int} expires 保存时间(单位:小时)
 * @param {string} path 保存路径
 * @param {string} domain
 * @param {string} secure
 */
export const setCookie = (name, value, expires, path, domain, secure) => {
  let str = name + "=" + encodeURIComponent(value);
  if (expires > 0) {
    let date = new Date();
    date.setTime(date.getTime() + expires * 3600 * 1000);
    str += ";expires=" + date.toGMTString();
  }
  if (path) {
    str += ";path=" + path;
  }
  if (domain) {
    str += ";domain=" + domain;
  }
  if (secure) {
    str += ";secure=" + secure;
  }
  document.cookie = str;
};

/* 4.读取cookie
 * @param {string} name cookie名称
 * @return {string} value cookie值
 */
export const getCookie = name => {
  let start = document.cookie.indexOf(name + "=");
  if (!start && name !== document.cookie.substring(0, name.length)) {
    return "";
  }
  if (start === -1) {
    return "";
  }
  let len = start + name.length + 1;
  let end = document.cookie.indexOf(";", len);
  if (end === -1) {
    end = document.cookie.length;
  }
  return decodeURIComponent(document.cookie.substring(len, end));
};

/*
 * 5.base64 明文简单加密
    @param {string} 加密内容
 * */
export const Base64encode = function(input) {
  // private method for UTF-8 encoding
  let utf8Encode = function(string) {
    string = string.replace(/\r\n/g, "\n");
    let utftext = "";
    for (let n = 0; n < string.length; n++) {
      let c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if (c > 127 && c < 2048) {
        utftext += String.fromCharCode(c >> 6 | 192);
        utftext += String.fromCharCode(c & 63 | 128);
      } else {
        utftext += String.fromCharCode(c >> 12 | 224);
        utftext += String.fromCharCode(c >> 6 & 63 | 128);
        utftext += String.fromCharCode(c & 63 | 128);
      }
    }
    return utftext;
  };
  let keyStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let output = "";
  let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  let i = 0;
  input = utf8Encode(input);
  while (i < input.length) {
    chr1 = input.charCodeAt(i++);
    chr2 = input.charCodeAt(i++);
    chr3 = input.charCodeAt(i++);
    enc1 = chr1 >> 2;
    enc2 = (chr1 & 3) << 4 | chr2 >> 4;
    enc3 = (chr2 & 15) << 2 | chr3 >> 6;
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output =
      output +
      keyStr.charAt(enc1) +
      keyStr.charAt(enc2) +
      keyStr.charAt(enc3) +
      keyStr.charAt(enc4);
  }
  return output;
};

/*
 * 6.base64 明文简单解密
    @param {string} 解密内容
 * */
export const Base64decode = function(input) {
  // private method for UTF-8 decoding
  let utf8Decode = function(utftext) {
    let string = "";
    let i = 0;
    let c = 0,
      c2 = 0,
      c3 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if (c > 191 && c < 224) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode((c & 31) << 6 | c2 & 63);
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(
          (c & 15) << 12 | (c2 & 63) << 6 | c3 & 63
        );
        i += 3;
      }
    }
    return string;
  };
  let keyStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let output = "",
    chr1,
    chr2,
    chr3,
    enc1,
    enc2,
    enc3,
    enc4,
    i = 0;
  let rule = /[^A-Za-z0-9+/=]/g;
  input = input.replace(rule, "");
  while (i < input.length) {
    enc1 = keyStr.indexOf(input.charAt(i++));
    enc2 = keyStr.indexOf(input.charAt(i++));
    enc3 = keyStr.indexOf(input.charAt(i++));
    enc4 = keyStr.indexOf(input.charAt(i++));
    chr1 = enc1 << 2 | enc2 >> 4;
    chr2 = (enc2 & 15) << 4 | enc3 >> 2;
    chr3 = (enc3 & 3) << 6 | enc4;
    output = output + String.fromCharCode(chr1);
    if (enc3 !== 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 !== 64) {
      output = output + String.fromCharCode(chr3);
    }
  }
  output = utf8Decode(output);
  return output;
};
